;(function($){
	
	var xOffset = -20; // x distance from mouse
    var yOffset = 20; // y distance from mouse  
	/**
	 * 验证类型
	 */
	var ValidType = {
			url:{
				required:false,
				value:"",
				validate:"^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$"
			},
			int:{
				required:false,
				min:null,
				max:null,
				validate:function(v){
					var reg = /^(-|\+)?\d+$/ ;
					if (!reg.test(v))return false;
					if (this.min != null && parseInt(v) < parseInt(this.min))return false;
					if (this.max != null && parseInt(v) > parseInt(this.max)) return false;
					return true;
				}
			},
			range:{
				required:false,
				min:0,
				max:128,
				reg:null,
				value:"",
				validate:function(v){
					if (v.length < this.min || v.length > this.max ){
						return false;
					}
					if (this.reg){
						var regExp = new RegExp(validateAction);
						return regExp.test(value);
					}
					return true;
				}
			},
			trigger:{
				required:false,
				validate:function(){return true;}
			}
	};
	
	var ValidHelper = {
			valid:function(v){
				var validateAction = v.validate;
				var value = this.getValue();
				//1.是否可以为空
				var validResult = false;
				if (!value){
					validResult = !v.required;
				} else {
					//1.如果是字符串，则是正则表达式验证
					if (typeof validateAction == 'string'){
						var reg = new RegExp(validateAction);
						validResult = reg.test(value);
					} else if (typeof validateAction == 'function'){
						validResult = validateAction.call(v,value);
					}
				}
				//提示验证结果
				ValidHelper.renderValidResult.call(this,validResult);
				return validResult;
			},
			renderValidResult:function(r){
				var f = this.field;
				if (f.data('orig_border') == undefined){
					var oborder = f.css('border');
					var ocolor = f.css('color');
					f.data('orig_border',oborder);
					f.data('orig_color',ocolor);
				}
				if(r){
					f.css('border',f.data('orig_border'));
					f.css('color',f.data('orig_color'));
				}else{
					f.css('border',"2px solid #FF0000");
					f.css("color","red");
				}
			},
			showTip:function(e,tip){
				var top = (e.pageY + yOffset);
				var left = (e.pageX + xOffset);
				$('body').append("<p id='tip' style='position: absolute; padding: 10px; left: 5px; font-size: 0.8em; background-color: white; border: 1px solid #a6c9e2; -moz-border-radius: 5px; -webkit-border-radius: 5px; z-index: 9999;'>" +
								"<img id='tip_arrow' src='"+cpath+"/resources/portal/js/validator/tip_arrow.png' style='position: absolute; top: -10px; left: 5px'/>" + tip + "</p>" );
				$('p#tip').css("top", top+"px").css("left", left+"px");
				$('p#tip').bgiframe();
			},
			moveTip:function(e){
				var top = (e.pageY + yOffset);
				var left = (e.pageX + xOffset);
				$("p#tip").css("top", top+"px").css("left", left+"px");
			},
			removeTip:function(){
				$("p#tip").remove();
			}
	};

	
	/**
	 * 每一个的表单元素的验证器
	 */
	var ValidField = function($this,form,data){
		this.field = $this;
		this.validator = {};
		this.form = form;
		var v = ValidType[data.type];
		//如果没有自定义值，则默认初始化
		if (data.value == undefined){
			data.value = this.getValue();
		}
		$.extend(this.validator,v,data);
		v = this.validator;
		var _this = this;
		if (v.tip){
			$this.hover(function(e){
				ValidHelper.showTip.call(_this,e, v.tip);
			},function(e){
				ValidHelper.removeTip.call(_this);
			}).mousemove(function(e){
				ValidHelper.moveTip.call(_this,e);
			});
		}
		//是否支持blur事件
		if (v.blur){
			$this.blur(function(){
				ValidHelper.valid.call(_this,v);
			});
		}
	};
	
	ValidField.prototype.resetValue = function(){
		this.validator.value = this.getValue();
	};
	
	ValidField.prototype.isEmpty = function(){
		var val = this.getValue();
		return !val;
	};
	
	ValidField.prototype.reset = function(){
		ValidHelper.renderValidResult.call(this, true);
	};
	ValidField.prototype.hasChanged = function(){
		var v = this.validator;
		return v.value != this.getValue();
	};
	
	ValidField.prototype.getValue = function(){
		return this.field.val();
	};
	
	ValidField.prototype.valid = function(){
		return ValidHelper.valid.call(this,this.validator);
	};
	
	/**
	 * 这个是针对每个子表单
	 */
	var Validform = function($f,data){
		this.form = $f;
		var _this = this;
		this.opt = {};
		$.extend(this.opt,Validform.defaults,data);
		$f.find("[data-type]").each(function(i,field){
			_this.addField($(this));
		});
	};
	
	Validform.prototype.addField = function($field){
		if (!$field.data("valid_field")){
			var validData = $field.data();
			var vf = new ValidField($field,this.form,validData);
			$field.data("valid_field",vf);
		}
	};
	

	

	
	Validform.prototype.isIgnore = function(){
		//如果支持忽略
		return this.iterator(function(field){
			return !field.hasChanged();
		}, true);
	};
	
	Validform.prototype.resetValue = function(){
		//如果支持忽略
		return this.iterator(function(field){
			field.resetValue();
		}, true);
	};
	Validform.prototype.iterator=function(fun,interrrup){
		return _iterator.call(this,this.form.find("[data-type]"),function(i,field){
			var validField = $(field).data("valid_field");
			if (validField){
				return fun.call(this,validField);
			}
		},interrrup);
	};
	
	var _iterator = function(iterator,fun,interrrup){
		var result = true;
		var _this = this;
		iterator.each(function(i,item){
			var r = fun.call(_this,i,item);
			if (r === false){
				result = false;
				//如果支持打断
				if (interrrup){
					return false;
				}
			}
		});
		return result;
	};
	Validform.prototype.valid = function(){
		//如果该表单验证忽略，则直接返回验证通过
		if (this.isIgnore()){
			//清除表单控件的错误样式
			this.iterator(function(field){
				field.reset();
			});
			return true;
		}
		return this.iterator(function(field){
			return field.valid();
		});
	};
	
	Validform.defaults = {
			ignore:true
	};
	
	
	var Valid=function($this,options){
		var opt =$.extend({},Valid.defaults,options);
		var _this = this;
		this.forms = $this;
		$this.each(function(i,f){
			_this.addForm($(f));
		});
	};
	
	Valid.prototype.addForm = function($f){
		if (!$f.data("valid_form")){
			var data = $f.data();
			var vf = new Validform($f,data);
			$f.data("valid_form",vf);
			this.forms = this.forms.add($f);
		}
	};
	
	Valid.prototype.removeForm = function($f){
		this.forms = this.forms.not($f);
		$($f).data("valid_form",null);
		$($f).remove();
	};
	Valid.prototype.valid = function(){
		return _iterator.call(this,this.forms, function(i,f){
			if ($(f).data("valid_form")){
				var validForm = $(f).data("valid_form");
				return validForm.valid();
			}
		});
	};
	Valid.prototype.destroy = function(){
		var forms = this.forms;
		forms.data("valid_plugin",null);
		forms.remove();
	};
	Valid.prototype.hasChanged=function(){
		var result = false;
		this.forms.each(function(i,f){
			if ($(f).data("valid_form")){
				var validForm = $(f).data("valid_form");
				if (!validForm.isIgnore()){
					result = true;
					return false;
				}
			}
		});
		return result;
	};
	
	Valid.prototype.resetValue = function(){
		this.forms.each(function(i,f){
			if ($(f).data("valid_form")){
				var validForm = $(f).data("valid_form");
				if (validForm){
					validForm.resetValue();
				}
			}
		});
	};
	
	var cpath;
	$.fn.valid=function(path,options){
		if (path != undefined){
			cpath = path;
		}
		var $this = $(this);
		if ($this.data("valid_plugin")){return $this.data('valid_plugin'); }
		var valid = new Valid(this,options);
		$this.data('valid_plugin', valid);
        return valid;
	};
	Valid.defaults={
			submit:function(){
			}
	};
})(jQuery);


;(function($){
	var DEFAULTS = {
			onSelect:$.noop,
			onEdit:$.noop
	};
	var _init = function($s,$i){
		//1.select绑定change事件，让选择的项的text设置到input上
		$s.on("change.editbox",$.proxy(_onSelect,this));
		//2.默认将select的text设置到input上
		_setText.call(this);
		//3.绑定input的获取焦点和失去焦点的事件
		var _this = this;
		$i.on("focus.editbox",function(){
			//移除select的选择事件,增加input的change事件
			$s.off("change.editbox");
			$i.on("change.editbox",$.proxy(_onEdit,_this));
		}).on("blur.editbox",function(){
			$i.off("change.editbox");
			$s.on("change.editbox",$.proxy(_onSelect,_this));
		});
	};
	
	var _setText = function(){
		var t = this.$s.find("option:selected").text();
		this.$i.val(t);
	};
	var _setDefaultSelect = function(){
		this.$s.val(0);
	};
	
	var _onSelect = function(){
		_setText.call(this);
		this.opt.onSelect.call(this);
	};
	
	var _onEdit = function(){
		_setDefaultSelect.call(this);
		this.opt.onEdit.call(this);
	};
	
	var Editbox = function($s,$i,options){
		this.$s = $s;
		this.$i = $i;
		var opt = {};
		this.opt = opt;
		$.extend(opt,DEFAULTS,options);
		_init.call(this, $s,$i);
	};
	
	Editbox.prototype.getValue = function(){
		return this.$s.val();
	};
	Editbox.prototype.getText= function(){
		return this.$i.val();
	};
	
	$.fn.editbox=function(options){
		this.each(function (i,e){
			if (!$(this).data("editbox_plugin")){
				var $s = $(this).find("select");
				var $i = $(this).find("input");
				var box = new Editbox($s,$i,options);
				$(this).data('editbox_plugin', box);
			}
		});
        return this;
	};
})(jQuery);

;(function($,win){
	
	var config = {
			cpath:"",
			trip:{
				valid:{
					form:".trip-step4-editform-form",
					options:{}
				},
				upload:{
					uploadDiv:null,
					options:{}
				},
				formdata:$.noop,
				formurl:"",
				datetime:null
			},
			flight:{
				valid:{
					form:".trip-step4-editform-form",
					options:{}
				},
				formdata:$.noop,
				formurl:"",
				datetime:null,
				createFlightView:$.noop,
				deleteurl:null,
				flightTitle:".trip-step4-editform-form-title",
				deleteButton:"<a class='trip-step4-remove' href='javascript:void(0)'>删除</a>",
				flightId:"[name=flightId]",
				addButton:".trip-step4-rightbtnadd input"
				
			},
			daily:{
				valid:{
					form:".trip-step4-editform-form",
					options:{}
				},
				upload:{
					uploadDiv:null,
					options:{}
				},
				formdata:$.noop,
				formurl:""
//				createFlightView:$.noop,
//				deleteurl:null,
//				locationTitle:".trip-step4-editform-form-title",
//				deleteButton:"<a class='trip-step4-remove' href='javascript:void(0)'>删除</a>",
//				locationId:"[name=locationId]",
//				addButton:".trip-step4-rightbtnadd input"
			}
	};
	win.TripEditHelper = function(options){
		$.extend(true,config,options);
		this.steps = [];
	};
	
	TripEditHelper.prototype.init = function(index,$step,wizard){
		var step = this.steps[index];
		if (!step){
			//获取他的Id
			var sid = $step.attr("href");
			var $stepContent = $(sid);
			if ($stepContent.length ==0){
				throw "step id error,not macth content";
			}
			if (index == 0){
				step = new Trip($stepContent);
			} else if (index == 1){
				step = new TripFlight($stepContent,wizard);
			}else {
				step = new TripDaily(index - 2,$stepContent,wizard);
			}
			this.steps[index] = step;
		}
	};
	
	TripEditHelper.prototype.valid = function (index,$step,successCall){
		var step = this.steps[index];
		return step.valid(successCall);
	};
	TripEditHelper.prototype.destroy = function(index,$step){
		if (index == 1){
			var step = this.steps[index];
			this.steps[index] = null;
			step.validator.destroy();
		}
	};
	var _validform = function(valid,successCall){
		if (valid.hasChanged()){
			if (valid.valid()){
				var data = this.getFormData();
				var url = this.getFormURL();
				var error = this.getError();
				$.post(url, data,function(result){
					if (result.resultCode === '00000000') {
						//处理完成结果
						if ($.isFunction(successCall)){
							successCall(result);
						}
						valid.resetValue();
					} else {
						alert(error);
					}
				},'json');
				//TODO 这里需要调整，需要保存成功后才能提交
				return true;
			}
			//表单验证不通过
			return false;
		}
		//表单没有发生改变
		if ($.isFunction(successCall)){
			successCall(true);
		}
		return true;
	};
	
	var _deleteform = function(url,id,$form){
		//1.弹出提示框，确认用户是否需要删除
		var _this = this;
		$.dialog({
			title:"确认",
			content:"是否需要删除?",
			okValue:"确认",
			ok:function (){
				var that = this;
				function deleteAfter(){
	        		//$form.remove();
			    	_this.validator.removeForm($form);
	        		_this.wizard.updateHeight();
	        		that.close().remove();
	    		}
	    		if (id){
	    			//存在航班id,则需要删除数据库
	    			$.post(url, {"id":id},function(result){
	    				if (result.resultCode === '00000000') {
	    					deleteAfter();
	    				} else {
	    					//信息框例二
	    					that.content("删除失败");
	    				}
	    			},'json');
	    		} else {
	    			deleteAfter();
	    		}
			},
			cancelValue:"取消",
			cancel:function (){
			},
			lock: true
		});
	};
	
	var _initDatepicter = function($target){
		$target.datetimepicker({lang:'ch',step:1,format:'Y/m/d H:i:00',inline:false});
	};
	
	var Trip = function($c){
		this.c = $c;
		var setting = config.trip;
		//1.初始化表单的验证
		this.validator = $(setting.valid.form,$c).valid(config.cpath,setting.valid.options);
		//2.初始化上传的插件
		$(setting.upload.uploadDiv,$c).fileapi(setting.upload.options);
		//初始化表单的日历控件
		_initDatepicter.call(this,$(setting.datetime,$c));
	};
	
	Trip.prototype.valid = function(successCall){
		return _validform.call(this,this.validator,successCall);
	};
	
	Trip.prototype.getFormData = function(){
		return config.trip.formdata.call(this,this.c);
	};
	Trip.prototype.getError = function(){
		return "行程编辑失败";
	};
	Trip.prototype.getFormURL = function(){
		return config.trip.formurl;
	};
	
	var TripFlight = function($c,wizard){
		this.c = $c;
		var s = config.flight;
		this.setting = s;
		this.wizard = wizard;
		//3.添加编辑框
		$(s.editbox,$c).editbox();
		//1.初始化表单的验证
		var sform = s.valid.form;
		var flights = $(sform,$c);
		
		this.validator = flights.valid(config.cpath,s.valid.options);
		//2.初始化表单的日历控件
		_initDatepicter.call(this,$("form "+s.datetime,$c));
		//3.初始化航班的添加
		var _this = this;
		$(s.addButton,$c).click(function(){
			//1.创建航班的视图
			_this.addFlight($(sform,$c).length +1);
		});
		//4.初始化航班的删除，第三个航班开始增加删除
		if (flights.length > 2){
			for (var i = 2;i<flights.length;i++){
				var $flight = flights[i];
				this.addDeleteForFlight(i + 1, $flight);
			}
		} else {
			//5.初始化航班的默认两个
			var i = flights.length;
			if (i == 0){
				this.addFlight(1);
				this.addFlight(2);
			} else if (i == 1){
				this.addFlight(2);
			}
		}
	};
	TripFlight.prototype.valid = function(successCall){
		return _validform.call(this,this.validator,successCall);
	};
	
	TripFlight.prototype.addDeleteForFlight = function(flightNo,$flight){
		var s = this.setting;
		var $delBut = $(s.deleteButton);
		var _this = this;
		$delBut.click(function(){
			_this.deleteFlight(flightNo,$flight);
		});
		$(s.flightTitle,$flight).append($delBut);
	};
	
	TripFlight.prototype.addFlight = function(flightNo){
		var s = this.setting;
		var $flight = s.createFlightView.call(this,flightNo,this.c);
		$(s.editbox,$flight).editbox();
		//1.添加表单验证
		this.validator.addForm($flight);
		//2.初始化表单的日历控件
		_initDatepicter.call(this,$(s.datetime,$flight));
		
		
		//如果航班号大于2，则需要绑定添加删除功能
		var _this = this;
		if(flightNo > 2){
			this.addDeleteForFlight(flightNo, $flight);
		}
		//3.添加到界面
		$("form",this.c).append($flight);
		this.wizard.updateHeight();
	};
	
	TripFlight.prototype.deleteFlight = function(flightNo,$flight){
		//1.弹出提示框，确认用户是否需要删除
		var s = this.setting;
		_deleteform.call(this, s.deleteurl,$(s.flightId,$flight).val(),$flight);
	};
	TripFlight.prototype.getFormData = function(){
		return this.setting.formdata.call(this,this.c);
	};
	TripFlight.prototype.getError = function(){
		return "行程航班编辑失败";
	};
	TripFlight.prototype.getFormURL = function(){
		return this.setting.formurl;
	};
	
	var TripDaily = function(daliyNo,$c){
		this.dailyNo = daliyNo + 1;
		this.c = $c;
		var s = config.daily;
		this.setting = s;
		//1.初始化表单的验证
		var sform = s.valid.form;
		var locations = $(sform,$c);
		this.locations = locations;
		this.validator = locations.valid(config.cpath,s.valid.options);
		//3.初始化航班的添加
//		var _this = this;
//		$(s.addButton,$c).click(function(){
//			//1.locations的第一个是天的的基础信息，所以不需要加1
//			_this.addLocation(locations.length);
//		});
//		//4.初始化航班的删除，第三个航班开始增加删除
//		if (locations.length > 2){
//			for (var i = 2;i<locations.length;i++){
//				var $loc = locations[i];
//				this.addDeleteForLocation(i + 1, $loc);
//			}
//		} else {
//			//5.初始化航班的默认两个
//			var i = locations.length;
//			if (i == 1){
//				this.addLocation(1);
//			}
//		}
		//5.初始化上传的插件
		if (s.upload.uploadDiv){
			$(s.upload.uploadDiv,$c).each(function(i,e){
				var opt = $.extend({},s.upload.options);
				opt.data = $(this).data();
				$(this).fileapi(opt);
			});
		}
	};
	TripDaily.prototype.valid = function(successCall){
		return _validform.call(this,this.validator,successCall);
	};
	
//	TripDaily.prototype.addDeleteForLocation = function(locNo,$loc){
//		var s = this.setting;
//		var $delBut = $(s.deleteButton);
//		var _this = this;
//		$delBut.click(function(){
//			_this.deleteLocation(locNo,$loc);
//		});
//		$(s.locationTitle,$loc).append($delBut);
//	};
	
//	TripDaily.prototype.addLocation = function(locNo){
//		var s = this.setting;
//		var $loc = s.createFlightView.call(this,locNo,this.c);
//		//1.添加表单验证
//		this.validator.addForm($loc);
//		//如果航班号大于2，则需要绑定添加删除功能
//		var _this = this;
//		if(locNo > 2){
//			this.addDeleteForLocation(locNo, $loc);
//		}
//		//初始化上传插件
//		$(s.upload.uploadDiv,$loc).fileapi(s.upload.options);
//		//3.添加到界面
//		$("form",this.c).append($loc);
//	};
//	
//	TripDaily.prototype.deleteLocation = function(locNo,$loc){
//		var s = this.setting;
//		_deleteform.call(this, s.deleteurl,$(s.locationId,$loc).val(),$loc);
//	};
	
	TripDaily.prototype.getFormData = function(){
		return this.setting.formdata.call(this,this.c);
	};
	TripDaily.prototype.getError = function(){
		return "行程第"+this.dailyNo+"天编辑失败";
	};
	TripDaily.prototype.getFormURL = function(){
		return this.setting.formurl;
	};

})(jQuery,window);

